﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using SdmxMl.Common;

namespace SdmxMl.UiEditors.UC
{
    public partial class UcAttributeValueHtml : UserControl
    {
        private IReportedValue metadataVal;
        private readonly Regex _reLink = new Regex("href=['\"](?<link>.*?)['\"]");
        private Dictionary<Rectangle, Uri> _links = new Dictionary<Rectangle, Uri>();
        private bool _isEditMode;

        public bool IsFinal
        {
            set
            {
            }
        }
        public IReportedValue MetaDataValue
        {
            set
            {
                metadataVal = value;

                //Retrieve value string
                string txt = metadataVal.SimpleValue;
                if (metadataVal.InternationalizedValue != null)
                    txt = metadataVal.InternationalizedValue.IsEmpty ? string.Empty : metadataVal.InternationalizedValue.ToString();

                HTMLEdit.Document.Body.InnerHtml = txt;
             //   HTMLEdit.Document.Body.Document.Write(txt);


                RecordLinkPositions();

                //         mshtml.IHTMLDocument2 htmlDoc = HTMLEdit.Document.DomDocument as mshtml.IHTMLDocument2;
                //         htmlDoc.designMode = "On";



            }
        }

        public string Content
        {
            get { return HTMLEdit.Document == null ? string.Empty : HTMLEdit.Document.Body.InnerHtml; }
        }


        public UcAttributeValueHtml()
        {
            InitializeComponent();
            HTMLEdit.DocumentText = "<html><body></body></html>";

            HTMLEdit.Navigating +=
                  new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
            HTMLEdit.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HTMLEdit_DocumentCompleted);

            HTMLEdit.Document.Click += Document_Click;
            HTMLEdit.Document.MouseMove += Document_MouseMove;


            System.Windows.Forms.HtmlDocument doc = this.HTMLEdit.Document;
            doc.ExecCommand("EditMode", false, null);
            _isEditMode = true;

             //HTMLEdit.Document.Body.con
        }

        void HTMLEdit_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
        }

        private void webBrowser1_Navigating(object sender,
            WebBrowserNavigatingEventArgs e)
        {
            try
            {

                e.Cancel = true;
                if (e.Url != null)
                    System.Diagnostics.Process.Start(e.Url.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }


        private void Document_MouseMove(object sender, HtmlElementEventArgs e)
        {
            if (!_isEditMode) return;
            ChangeCursorIfOverLink(e);
        }

        private void ChangeCursorIfOverLink(HtmlElementEventArgs e)
        {
            foreach (KeyValuePair<Rectangle, Uri> link in _links)
            {
                if (CursorWithinControl(e, link.Key))
                {
                    if (Cursor.Current != Cursors.Hand)
                        Cursor.Current = Cursors.Hand;
                    return;
                }
            }
            Cursor.Current = Cursors.Default;
        }

        private void Document_Click(object sender, HtmlElementEventArgs e)
        {
            if (e.AltKeyPressed)
                return;
            NavigateLinkInEditMode(e);
        }

        private void NavigateLinkInEditMode(HtmlElementEventArgs e)
        {
            if (_isEditMode)
            {
                foreach (KeyValuePair<Rectangle, Uri> link in _links)
                {
                    if (CursorWithinControl(e, link.Key))
                    {
                        System.Diagnostics.Process.Start(link.Value.ToString());
                        return;
                    }
                }
            }
        }

        private bool CursorWithinControl(HtmlElementEventArgs e, Rectangle rectangle)
        {
            // Beuark needed to detect link when scrolling html frame Only OK for Win 7
         //   mshtml.IHTMLDocument2 htmlDoc = HTMLEdit.Document.DomDocument as mshtml.IHTMLDocument2;
         //   int scv = ((IHTMLElement2)htmlDoc.body).scrollTop;
            int scv = HTMLEdit.Document.GetElementsByTagName("body")[0].ScrollTop;
            return e.MousePosition.X >= rectangle.Left
                       && e.MousePosition.X <= rectangle.Left + rectangle.Width
                       && e.MousePosition.Y >= rectangle.Top - scv
                       && e.MousePosition.Y <= rectangle.Top + rectangle.Height - scv;

            
        }


        private void RecordLinkPositions()
        {
            _links.Clear();
            foreach (HtmlElement element in HTMLEdit.Document.All)
            {
                if (element.TagName == "A")
                {
                    string url = _reLink.Match(element.OuterHtml).Groups["link"].Value;
                    _links.Add(element.OffsetRectangle, new Uri(url));
                }
            }
        }

        private void toolStripButtonInsertLink_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("CreateLink", true, null);

        }

        private void toolStripButtonBold_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("Bold", false, null);

        }

        private void toolStripButtonItalic_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("Italic", false, null);

        }

        private void toolStripButtonUnderline_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("Underline", false, null);

        }

        private void toolStripButtonUnOrdList_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("InsertUnorderedList", false, null);

        }

        private void toolStripButtonOrdList_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("InsertOrderedList", false, null);

        }

        private void toolStripButtonLeft_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("JustifyLeft", false, null);

        }

        private void toolStripButtonCenter_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("JustifyCenter", false, null);

        }

        private void toolStripButtonRight_Click(object sender, EventArgs e)
        {
            this.HTMLEdit.Document.ExecCommand("JustifyRight", false, null);
        }
    }
    
}
